﻿using SharPy.Common;
using SharPy.GameObjects;
using SharPy.GameSaves;
using SharPy.Interface;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace SharPy
{
    public partial class SavePage
    {
        private NavigationHelper navigationHelper;
        private ObservableDictionary defaultViewModel = new ObservableDictionary();

        clGame CurrentGame;

        void InitPage()
        {
            this.navigationHelper = new NavigationHelper(this);
            this.navigationHelper.LoadState += this.NavigationHelper_LoadState;
            this.navigationHelper.SaveState += this.NavigationHelper_SaveState;
        }

        #region Buttons
        private async void ListView_ItemClick(object sender, ItemClickEventArgs e)
        {
            var item = e.ClickedItem as SaveDataItem;

            if (item.LineNo != 0)
            {
                if (await clDialogs.OverwriteSave())
                {
                    await clGameSave.WriteSave(CurrentGame, item.UniqueId);
                }
                else return;
            }
            else
            {
                await clGameSave.WriteSave(CurrentGame, item.UniqueId);
            }
            var eDataGroup = await SaveDataSource.GetGroupAsync("SaveGroup", CurrentGame.RootFolder);
            this.DefaultViewModel["Items"] = eDataGroup.Items;
        }

        private void backButton_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            Frame.GoBack();
        }
        #endregion

        #region Регистрация NavigationHelper


        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (e.Parameter.GetType() == typeof(clGame))
                this.CurrentGame = e.Parameter as clGame;
            this.navigationHelper.OnNavigatedTo(e);
            this.defaultViewModel["GameTitle"] = CurrentGame.Name;
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            this.navigationHelper.OnNavigatedFrom(e);
        }
        public NavigationHelper NavigationHelper
        {
            get { return this.navigationHelper; }
        }

        public ObservableDictionary DefaultViewModel
        {
            get { return this.defaultViewModel; }
        }

        private async void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {
            var eDataGroup = await SaveDataSource.GetGroupAsync("SaveGroup", CurrentGame.RootFolder);
            if (eDataGroup != null)
                this.DefaultViewModel["Items"] = eDataGroup.Items;
        }

        private void NavigationHelper_SaveState(object sender, SaveStateEventArgs e)
        {
        }
        #endregion


    }
}